package com.wteam.dragon.system.aop.log.controller.service.impl;

import cn.hutool.json.JSONObject;
import com.wteam.dragon.system.aop.log.controller.pojo.bean.Log;
import com.wteam.dragon.system.aop.log.controller.mapper.LogMapper;
import com.wteam.dragon.system.aop.log.controller.service.LogService;
import com.wteam.dragon.system.util.StringUtils;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;

/**
 * @Author 陈晓辉
 * @Date 2020/4/1 23:56
 */
@Service
@RequiredArgsConstructor
public class LogServiceImpl implements LogService{
    private final LogMapper logMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addLog(String username, String browser, String ip, ProceedingJoinPoint joinPoint, Log log){

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        com.wteam.dragon.system.aop.log.log.Log aopLog = method.getAnnotation(com.wteam.dragon.system.aop.log.log.Log.class);

        // 方法路径
        String methodName = joinPoint.getTarget().getClass().getName()+"."+signature.getName()+"()";

        StringBuilder params = new StringBuilder("{");
        //参数值
        Object[] argValues = joinPoint.getArgs();
        //参数名称
        String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
        if(argValues != null){
            for (int i = 0; i < argValues.length; i++) {
                params.append(" ").append(argNames[i]).append(": ").append(argValues[i]);
            }
        }
        // 描述
        if (log != null) {
            log.setDescription(aopLog.value());
        }
        assert log != null;
        log.setRequestIp(ip);

        String loginPath = "login";
        if(loginPath.equals(signature.getName())){
            try {
                assert argValues != null;
                username = new JSONObject(argValues[0]).get("username").toString();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        log.setAddress(StringUtils.getCityInfo(log.getRequestIp()));
        log.setMethod(methodName);
        log.setUsername(username);
        log.setParams(params.toString() + " }");
        log.setBrowser(browser);
        logMapper.insert(log);
    }
}
